import time

import re
from PyQt4.QtCore import QThread, pyqtSignal, QUrl
import common
from common.SystemOperation import getData, setData
from common.constant import appWindows
from pyquery import PyQuery as pq


class BrowserController(QThread):
    #定义信号,定义参数为str类型
    _signal=pyqtSignal(str)

    def __init__(self,name=None):
        # 0: 初始化  1:正在进行中  2: 已完成 3:暂停
        self.status=0
        self.htmlStr=None
        self.craUrl = None
        self.name = name
        self.browser = None
        # self.thread = threading.Thread(target=self.run,name=name)
        super(BrowserController,self).__init__()

    def reqHandler(self,str):
        print(str)
        self.browser.load(QUrl(str))
        return
    def startMain(self):
        self.browser = common.constant.appWindows.addTabBowser("one")
        self._signal.connect(self.reqHandler)
        self.start()
        self.browser.page().loadFinished.connect(self.finished)
        # self.craBrowser.page().toHtml(self.toHtmls)
        # dataOperation.setdefault(self.name,(browser,self))
        # self.thread.start()

    def finished(self):
        strHtml = self.browser.page().mainFrame().toHtml()
        self.htmlStrs(strHtml)

    def htmlStrs(self,retHtmlStr):
        strVal = str(retHtmlStr)
        if strVal.find('密码登录')>-1 :
            self.status = 3
        elif strVal.strip() == '':
            self.status = 1
        else:
            self.status = 2
            self.htmlStr = strVal
            dataks = self.handle()
            total = dataks.get("total")
            if total != None and int(self.craUrl.params.get("s")) <= int(total):
                self.backCraUrl()

         # print(args)
    def load(self):
        params = self.craUrl.params
        url = self.craUrl.url+"?"+"q="+params.get("q")+"&s="+str(params.get("s")*44)
        self.craUrl.reqNum = self.craUrl.reqNum+1
        self._signal.emit(url)
        
    def run(self):
        while True:
            print("status:"+str(self.status))
            if self.status == 0 :
                # time.sleep(3)
                self.craUrl = getData()
                if  self.craUrl!= None:
                    self.load()
                    self.status = 1
            elif self.status == 1:
                if  self.craUrl.reqNum == 5:
                    self.backCraUrl()
                    continue
                elif self.craUrl.reqNum < 5 :
                    self.load()
            elif self.status ==2 :
                print(self.htmlStr)
                self.htmlStr = None
                # self.backCraUrl()
                self.status = 0
                time.sleep(2)
                continue
            elif self.status ==3 :
                time.sleep(25)
            time.sleep(5)

    def backCraUrl(self):
        if self.craUrl.params.get("s")>99:
            return
        self.craUrl.params = {"q": self.craUrl.params.get("q"),"s": int(self.craUrl.params.get("s"))+1}
        self.craUrl.reqNum = 0
        setData(self.craUrl)

    def handle(self):
        data = {}
        doc = pq(self.htmlStr)
        total = doc.find(".total").text()
        if total !=None :
           nums = re.findall(r"\d+\.?\d*", total)
           if nums != None and len(nums) >0:
            data.setdefault("total",nums[0])
        print("total:"+total)
        itemDatas=[]
        items = doc.find("div[data-category='auctions']")
        if items!= None and items.size() >0 :
           for index in items :
               item = {}
               docIndex = pq(index)
               sales = docIndex.find("div[class='deal-cnt']")
               if sales != None:
                   salesText = sales.text()
                   salesValue = re.findall(r"\d+\.?\d*", salesText)[0]
                   item.setdefault("sales",salesValue)
               else:
                   sales = None
               rowTitle = docIndex.find(".J_ClickStat")
               if rowTitle !=None:
                   rowTitle = rowTitle.text()
                   item.setdefault("rowTitle",rowTitle)
               else:
                   rowTitle = None
               nidEl = docIndex.find(".J_ClickStat").attr("data-nid")
               if nidEl != None:
                   item.setdefault("nid",nidEl)
               itemDatas.append(item)
        data.setdefault("items",itemDatas)
        return data